package com.conv.shop.business.controller;

import com.conv.shop.business.domain.Address;
import com.conv.shop.business.domain.Consumer;
import com.conv.shop.business.req.ToConsumerReq;
import com.conv.shop.business.req.StoreUserPasswordReq;
import com.conv.shop.business.resp.ConsumerLoginResp;
import com.conv.shop.business.resp.ConsumerResp;
import com.conv.shop.business.resp.StoreLoginResp;
import com.conv.shop.business.service.AddressService;
import com.conv.shop.business.service.ConsumerService;
import com.conv.shop.business.service.ProductService;
import com.conv.shop.business.service.ShoppingCartService;
import com.conv.shop.business.util.JwtUtil;
import com.conv.shop.business.vo.CarVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/consumer")
public class ConsumerManageController {
    @Resource
    private ConsumerService consumerService;
    @Resource
    private ProductService productService;
    @Resource
    private AddressService addressService;
    @Resource
    private ShoppingCartService shoppingCartService;
    @GetMapping("/hello")
    public String hello(){
        return "Consumer,Hello SpringBoot";
    }

    @GetMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

    /**
     * 消费者注册接口
     * @param req
     * @return Map<String,Object>
     */
    @PostMapping("/register")
    public Map<String,Object> consumerRegister(@RequestBody ToConsumerReq req) {
        boolean result = consumerService.save(req);
        Map<String,Object> map = new HashMap<>();
        if(result){
            map.put("success",true);
            map.put("phone", req.getPhone());
            return map;
        }else{
            map.put("success",false);
            return map;
        }
    }

    /**
     * 消费者登录接口
     * @param consumerLoginReq
     * @param request
     * @return ResponseEntity<Map<String, Object>>
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody ToConsumerReq consumerLoginReq, HttpServletRequest request) {
        ConsumerLoginResp loginResp = consumerService.login(consumerLoginReq);
        if (loginResp != null) {
            request.getSession().setAttribute("phone", loginResp.getPhone());
            request.getSession().setAttribute("consumerId", loginResp.getConsumerId());
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("consumerId", loginResp.getConsumerId()); // 添加consumerId到响应
            response.put("phone", loginResp.getPhone()); // 添加phone到响应
            response.put("token",loginResp.getToken());
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "登录失败")) ;
        }
    }


    /**
     * 消费者信息修改接口
     * @param req
     * @return boolean
     */
    @PostMapping("/update")
    public boolean consumerUpdate(@RequestBody ToConsumerReq req){
      return consumerService.update(req);
    }

    /**
     * 用户列表查询
     * @return List<ConsumerResp>
     */
    @GetMapping("/list")
    public List<ConsumerResp> GetUserList(){
        return consumerService.getList();
    }

    /**
     * 用户详情查询
     * @param consumerId
     * @return Consumer
     */
    @GetMapping("/details")
    public Consumer getUserDetails(Integer consumerId) {
       return consumerService.getUserDetails(consumerId);
    }

    /**
     * 获取用户地址
     * @param consumerId
     * @return Address
     */
    @GetMapping("/getAddress")
    public Address getAddress(Integer consumerId){
       return addressService.getAddress(consumerId);
    }

    /**
     * 联表查询购物车和商品
     * @param phone
     * @return List<CarVo>
     */
    @GetMapping("/cartList")
    public List<CarVo> cartList(String phone){
        return shoppingCartService.getList(phone);
    }

//    @PostMapping("/updateCartQuantities")
//    public ResponseEntity<String> updateCartQuantities(@RequestBody List<CartItemUpdateReq> cartItems) {
//        try {
//            for (CartItemUpdateReq item : cartItems) {
//                productService.update(item.getProductId(), item.getQuantity());
//            }
//            return ResponseEntity.ok("购物车商品数量更新成功");
//        } catch (Exception e) {
//            // Log the exception details
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新购物车商品数量时发生错误");
//        }
//    }

    /**
     * 管理员登录
     * @param consumerLoginReq
     * @return StoreLoginResp
     */
    @PostMapping("/adminLogin")
    public ResponseEntity<StoreLoginResp> adminLogin(@Validated @RequestBody ToConsumerReq consumerLoginReq) {
        StoreLoginResp loginResp = consumerService.adminLogin(consumerLoginReq);
        if (loginResp != null) {
            return new ResponseEntity<>(loginResp, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 修改密码
     * @param storeUserPAsswordReq
     * @param request
     * @return boolean
     */
    @PostMapping("/storePasswd")
    public boolean StoreUserPasswd(@Validated @RequestBody StoreUserPasswordReq storeUserPAsswordReq, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null){
            return false;
        }
        if(!JwtUtil.validate(token)){
            return false;
        }
        storeUserPAsswordReq.setConsumerId(Integer.parseInt(JwtUtil.getUserNameByToken(token)));
        return consumerService.StoreUserPasswd(storeUserPAsswordReq);
    }
}
